﻿#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;

#endregion

namespace SilverBox.Logging.Providers
{
    public class TextLoggerProvider : ILoggerProvider
    {
        private string _path;

        public TextLoggerProvider()
        {
            Path = @"{0}";
            LogLifeDays = 15;
        }

        public string Path
        {
            get
            {
                var now = DateTime.Now;
                return string.Format("{0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}.log",
                              now.Year,
                              now.Month,
                              now.Day,
                              now.Hour,
                              now.Minute,
                              now.Second);
            }
            internal set { _path = value; }
        }

        public int LogLifeDays { get; set; }

        #region Implementation of ILogger

        public void Log(string entry)
        {
            try
            {
                Clean();
                const string format = "{0} :: {1}";
                SendLog(format, DateTime.Now.ToShortTimeString(), entry);
            }
            catch (Exception ex)
            {
                HasError = true;
                Error = ex;
            }
        }

        #endregion

        #region Implementation of ILoggerProvider

        public bool HasError { get; set; }

        public Exception Error { get; set; }

        #endregion

        private void SendLog(string s, params object[] args)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var file = @"Log\" + Path;
                using (var stm = store.OpenFile(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                {
                    // Move to the end
                    stm.Seek(0, SeekOrigin.End);

                    // Write the log
                    using (var writer = new StreamWriter(stm))
                    {
                        writer.WriteLine(s, args);
                    }
                }
            }
        }

        private void Clean()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.DirectoryExists("Log"))
                {
                    store.CreateDirectory("Log");
                }
                var logFiles = store.GetFileNames(@"Log\*");
                var names = new List<string>();
                for (var i = 0; i < LogLifeDays + 1; i++)
                {
                    names.Add(DateTime.Now.AddDays(-i).ToLongDateString());
                }
                var oldFiles = logFiles.Where(f => !names.Contains(f));
                foreach (var file in oldFiles)
                {
                    store.DeleteFile(file);
                }
            }
        }
    }
}